import { ref } from 'vue';
import { fetchCalculate, fetchGenerateReport } from '@/service/api';

export function useFormActions<T = any>(formId: string) {
  const loading = ref(false);

  // 计算
  async function calculate(data: any) {
    loading.value = true;
    try {
      const res = await fetchCalculate<T>(formId, data);
      return res;
    } finally {
      loading.value = false;
    }
  }

  // 生成报告并下载
  async function generateReport(data: any) {
    loading.value = true;
    try {
      // 1. fetchRes 的类型是 FlatResponseData<Blob,Response>
      const fetchRes = await fetchGenerateReport(formId, data);
      // 2. 真正的 Blob 在 fetchRes.data
      const blob = fetchRes.data;
      if (!blob) {
        // 处理错误：blob 不应为 null
        console.error('报告下载失败：未获取到二进制数据');
        return;
      }
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${formId}_report.docx`;
      a.click();
      URL.revokeObjectURL(url);
    } finally {
      loading.value = false;
    }
  }

  return {
    calculate,
    generateReport,
    loading
  };
}
